import time

import torch
import torchvision.datasets
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm

batch_size = 4

train_data = torchvision.datasets.CIFAR10("../dataset", train=True, download=True,
                                          transform=torchvision.transforms.ToTensor())
train_dataloader = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=0, drop_last=False)

test_data = torchvision.datasets.CIFAR10("../dataset", train=False, download=False,
                                         transform=torchvision.transforms.ToTensor())
test_dataloader = DataLoader(test_data, batch_size=batch_size, shuffle=True, num_workers=0, drop_last=False)


class MyMod(nn.Module):
    def __init__(self):
        super(MyMod, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(in_channels=3, out_channels=32, kernel_size=5, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(in_channels=32, out_channels=32, kernel_size=5, padding=2),
            nn.MaxPool2d(2),
            nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, padding=2),
            nn.MaxPool2d(2),
            nn.Flatten(),
            nn.Linear(in_features=1024, out_features=64),
            nn.Linear(in_features=64, out_features=10)
        )

    def forward(self, x):
        output = self.model(x)
        return output


device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print("start on {} device.".format(device))
train_data_size = len(train_data)
test_data_size = len(test_data)
print("训练数据集长度: {}".format(train_data_size))
print("测试数据集长度: {}".format(test_data_size))
# 创建网络模型
mymod = MyMod()
mymod = mymod.to(device)
# 损失函数
loss_fn = nn.CrossEntropyLoss()
loss_fn = loss_fn.to(device)

# 优化器
# learning_rate = 0.01
# 1e-2=1 x (10)^(-2) = 1 /100 = 0.01
learning_rate = 1e-2
optimizer = torch.optim.SGD(mymod.parameters(), lr=learning_rate)

# 训练的轮数
epoch = 1
for i in range(epoch):
    mymod.train()
    train_step = 0
    with tqdm(train_dataloader) as loop1:
        for imgs, targets in loop1:
            loop1.set_description(f'train Epoch [{i} / {epoch}]')

            imgs = imgs.to(device)
            targets = targets.to(device)
            outputs = mymod(imgs)

            loss = loss_fn(outputs, targets)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()

            if train_step % 1000 == 0:
                loop1.set_postfix(loss=loss.item())

            train_step += 1

    mymod.eval()
    test_total_loss = 0
    test_total_accuracy = 0
    test_step = 0
    # 去掉梯度
    with torch.no_grad():
        with tqdm(test_dataloader) as loop2:
            for imgs, targets in loop2:
                loop2.set_description(f'test Epoch [{i} / {epoch}]')

                imgs = imgs.to(device)
                targets = targets.to(device)
                outputs = mymod(imgs)

                loss = loss_fn(outputs, targets)
                test_total_loss += loss.item()
                # 统计在测试集上正确的个数，然后累加起来
                accuracy = (outputs.argmax(1) == targets).sum()
                test_total_accuracy += accuracy

                if test_step % 1000 == 0:
                    test_accuracy_rate = float(accuracy.item()) / float(len(targets))
                    loop2.set_postfix(loss=loss.item(), acc=test_accuracy_rate)

                test_step += 1

    print("测试集上的总体loss：{}".format(test_total_loss))
    # 精度=测试集上正确的总数/测试集的数量
    print("测试集上的总体accuracy：{}".format(test_total_accuracy / test_data_size))

torch.save(mymod, "./mymod.pth")
